package com.faxsun.admin.server.service.extention;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.broadleafcommerce.admin.server.service.extension.DefaultAdminCatalogExtensionHandler;
import org.broadleafcommerce.common.extension.ExtensionResultHolder;
import org.broadleafcommerce.common.extension.ExtensionResultStatusType;
import org.broadleafcommerce.core.catalog.domain.Product;
import org.broadleafcommerce.core.catalog.domain.ProductOptionValue;
import org.broadleafcommerce.core.catalog.domain.Sku;

import com.faxsun.core.catalog.domain.FSSku;
import com.faxsun.core.catalog.domain.FSSkuImpl;

public class FSAdminCatalogExtensionHandler extends DefaultAdminCatalogExtensionHandler {

	@Override
	public ExtensionResultStatusType persistSkuPermutation(Product product,
			List<List<ProductOptionValue>> permutationsToGenerate, ExtensionResultHolder<Integer> erh) {
		int numPermutationsCreated = 0;
		// For each permutation, I need them to map to a specific Sku
		for (List<ProductOptionValue> permutation : permutationsToGenerate) {
			if (permutation.isEmpty())
				continue;
			Sku permutatedSku = catalogService.createSku();
			permutatedSku.setProduct(product);
			Set<ProductOptionValue> permutationSet = new HashSet<ProductOptionValue>(permutation);
			permutatedSku.setProductOptionValuesCollection(permutationSet);
			if (permutatedSku instanceof FSSku) {
				FSSku permutatedFSSku = (FSSku) permutatedSku;
				FSSku defaultSku = (FSSku) product.getDefaultSku();
				permutatedFSSku.setForeignPrice(defaultSku.getForeignPrice());
				permutatedFSSku.setPriceCurrency(defaultSku.getPriceCurrency());
				permutatedFSSku.setShippingFee(defaultSku.getShippingFee());
				permutatedFSSku.setDescription(((FSSkuImpl) defaultSku).getShortDescription());
			}
			permutatedSku = catalogService.saveSku(permutatedSku);
			product.getAdditionalSkus().add(permutatedSku);
			numPermutationsCreated++;
		}
		if (numPermutationsCreated != 0) {
			catalogService.saveProduct(product);
		}
		erh.setResult(numPermutationsCreated);
		return ExtensionResultStatusType.HANDLED;
	}

}
